﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using RBS.Core.Model;
 
using RBS.Web.API.Models;

namespace RBS.Web.API.Areas.User.Controllers
{
    /// <summary>
    /// 订单
    /// </summary>
    public class OrderController : ApiController
    { 
        private ApiContext db = new ApiContext(); 
        /// <summary>
        /// 获取订单详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonData GetOrder(int id)
        {
          
            var jsonData = new JsonData { Success = true };
            var order = db.VOrder.Find(id);
            var orderModel = new OrderModel
            { 
                Order = order,
                Detail = db.VOrderDetails.Where(c => c.OrderId == id).ToList(), 
            }; 
            orderModel.Hotel = db.VHotel.FirstOrDefault(c => c.Id == orderModel.Order.H_Id);
            orderModel.OrderNum = orderModel.Detail.Sum(c => c.Num).ToString(CultureInfo.InvariantCulture);
            orderModel.OrderAmount = orderModel.Detail.Sum(c => c.Num* c.Price * c.Weight).ToString("N1");
            jsonData.Data = orderModel; 

          
            return jsonData;
        } 

        /// <summary>
        /// 获取用户订单
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public JsonData GetUserOrder(int uid, int page = 1, int limit = 5)
        {
            JsonData jsonData = new JsonData {Success = true};
            var items = db.VOrder.Where(c => c.U_Id == uid);
            int total = items.Count();
            double pageCount = Math.Ceiling((double)total / (double)limit);
            int totalPage = (int)pageCount;
            if (page > totalPage)
            {
                page = totalPage;
                jsonData.Data = null;
                jsonData.Count = 0;
                jsonData.Page = page;
                jsonData.PageSize = limit;
                jsonData.TotalPage = totalPage;
                jsonData.Success = false;
                jsonData.Error = "最大页数为：" + totalPage + "页";
                return jsonData;
            }
            jsonData.Data  = items.OrderByDescending(t => t.OrderTime).Skip((page - 1) * limit).Take(limit); 
            jsonData.Count = total;
            jsonData.Page = page;
            jsonData.PageSize = limit;
            jsonData.TotalPage = totalPage;

            return jsonData;
        }
         
        /// <summary>
        /// 新增订单
        /// </summary>
        /// <param name="model">订单实体</param>
        /// <returns></returns>
        public JsonData Post([FromBody]D_Order model)
        {
            var jsonData = new JsonData{Success = true};
            
                if (ModelState.IsValid)
                {

                    if (model.OrderChannel == "网站订单" && model.Id <= 0)
                    {
                        var item = db.Order.Add(model);
                        db.SaveChanges();
                        jsonData.Data = item.Id;
                    }
                    else
                    {
                        
                        try
                        {

                            model.OrderTime = Convert.ToDateTime(model.ReserveDate + " " + model.ReserveTime);  
                            DateTime time1 = model.OrderTime.AddHours(-3);
                            DateTime time2 = model.OrderTime.AddHours(3);
                            var error = new
                            {
                                t1 = time1,
                                t2 = time2,
                                seatid = model.DineTable 
                            };
                            var isSeat = new RBS.Core.BLL.D_Order().Seat(model.DineTable, time1, time2);
                           // RBS.Core.Logs.LogManager.WriteLog("tttt", ConvertJson.EntityToJson(error));
                            if (isSeat)
                            {
                                jsonData.Error = "当前座位已有预定，请选择别的座位";
                                jsonData.Success = false;
                                jsonData.Data = null;
                                RBS.Core.Logs.LogManager.WriteLog("座位信息", ConvertJson.EntityToJson(jsonData)); 
                                return jsonData;
                            }
                        }
                        catch (Exception ex)
                        {
                            RBS.Core.Logs.LogManager.WriteLog("bbbb", model.OrderTime.ToShortDateString());
                        } 

                        var item =
                            db.Order.FirstOrDefault(
                                c =>
                                c.H_Id == model.H_Id && c.U_Id == model.U_Id &&
                                model.OrderState == (int) RBS.Common.RBSEnums.OrderStatus.Ok);
                        if (item == null)
                        { 
                            var order = new RBS.Core.Model.D_Order
                                {
                                    OrderState = (int) RBS.Common.RBSEnums.OrderStatus.Ok,
                                    OrderTime = model.OrderTime,
                                    U_Id = model.U_Id,
                                    H_Id = model.H_Id,
                                    HotelName = model.HotelName,
                                    DineNum = model.DineNum,
                                    DineTable = model.DineTable, 
                                    OrderChannel = model.OrderChannel,
                                    ReserveDate = model.ReserveDate,
                                    ReserveTime = model.ReserveTime,
                                    CreateTime = DateTime.Now,
                                    LastModifyDate = DateTime.Now,
                                    ContactUser = model.ContactUser,
                                    ContactMobile = model.ContactMobile,
                                    PayTime = DateTime.Now
                                }; 
                                var seat = db.HotelSeat.Find(model.DineTable);
                                order.Dinecondition = seat.Category;

                               // RBS.Core.Logs.LogManager.WriteLog("Dinecondition", model.Dinecondition.ToString() + "," + seat.Name);
                            item = db.Order.Add(order);
                            db.SaveChanges();
                            //修改桌位状态
                            //  new SeatController().UpdateSeatStatus(item.DineTable, 1);
                            jsonData.Data = item;
                        }
                        else
                        {
                            jsonData.Data = item;
                        }
                    } 
                    return jsonData;
                }
                else
                {
                    jsonData.Success = false;
                    jsonData.Error = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState).ToString();
                    return jsonData;
                }
            
        }
       /* /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="orderid">订单ID</param>
        /// <param name="status">订单状态</param>
        /// <returns></returns>
        public JsonData GetOrderStatus(int orderid, int status)
        {

            var jsonData = new JsonData();
            if (!ModelState.IsValid)
            {
                jsonData.Success = false;
                jsonData.Error = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState).RequestMessage.ToString();
                return jsonData;
            }

            var model = db.Order.Find(orderid);
            model.OrderState = status; 
            db.Entry(model).State = EntityState.Modified;
            try
            {
                db.SaveChanges();
                jsonData.Data = Request.CreateResponse(HttpStatusCode.OK).ToString();
                jsonData.Success = true;
            }
            catch (DbUpdateConcurrencyException ex)
            {
                jsonData.Error = Request.CreateErrorResponse(HttpStatusCode.NotFound, ex).RequestMessage.ToString();
            }

            return jsonData;
        }*/

    }


 
}
